package com.example.yingjiguanli_demo.controller;

import com.example.yingjiguanli_demo.aspect.interfaces.RateLimiter;
import com.example.yingjiguanli_demo.aspect.interfaces.RequirePermission;
import com.example.yingjiguanli_demo.pojo.Posts;
import com.example.yingjiguanli_demo.pojo.Result;
import com.example.yingjiguanli_demo.service.IPostsService;
import com.example.yingjiguanli_demo.utils.UserUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author scj
 * @since 2024-11-04
 */
@RestController
@RequestMapping("api/v1/posts")
public class PostsController {
    @Autowired
    private IPostsService postsService;
    @Autowired
    private UserUtils userUtils;

    /***
     * 添加帖子
     * @param posts 帖子
     * @param sessionId sessionId
     * @return 添加结果
     */
    @ApiOperation(value = "添加帖子")
    @RequirePermission("admin")
    @RateLimiter
    @PostMapping("/add")
    public Result<T> addPosts(@RequestBody Posts posts
            , @CookieValue(name = "SESSIONID", required = false) String sessionId) {
        int userId = userUtils.getUserId(sessionId);
        return postsService.addPosts(posts, userId);
    }

    /**
     * 分页获取推文
     * @param pageNum 页码，从1开始
     * @param pageSize 每页条数
     * @return 推文分页结果
     */
    @ApiOperation(value = "分页获取推文")
//    @RequirePermission("user")
//    @RateLimiter
    @GetMapping("/paged")
    public Result<List<Posts>> getPosts(@RequestParam int pageNum, @RequestParam int pageSize) {
        return postsService.getPosts(pageNum, pageSize);
    }

    /***
     * 删除推文
     * @param id 推文id
     * @return 删除结果
     */
    @ApiOperation(value = "删除推文")
    @RequirePermission("admin")
    @RateLimiter
    @DeleteMapping("/delete/{id}")
    public Result<T> deletePosts(@PathVariable int id) {
        return postsService.deletePosts(id);
    }

    /***
     * 根据id查询推文
     * @param id 推文id
     * @return 查询结果
     */
    @ApiOperation(value = "根据id查询推文")
    @RequirePermission("user")
    @GetMapping("/getById/{id}")
    public Result<List<Posts>> getById(@PathVariable int id) {
        return postsService.getPostById(id);
    }
}
